﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.IncomingMaterialsManage;
using ProduceBasicData.Api.DTO.IncomingMaterialsDto;
using ProduceBasicData.Domain.IncomingMaterialsManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.IncomingMaterialsManage
{
    /// <summary>
    /// 获取来料检验信息
    /// </summary>
    public class GetIncomingInspectionHandler : IRequestHandler<GetIncomingInspectionCommand, ApiPaging<IncomingInspectionDto>>
    {
        // 修改Handler的构造函数
        private readonly IBaseRespository<IncomingInspection> _incomingInspectionRepository;
        private readonly IBaseRespository<InspectionScheme> _inspectionSchemeRepository;
        private readonly IMapper _mapper;

        public GetIncomingInspectionHandler(
            IBaseRespository<IncomingInspection> incomingInspectionRepository,
            IBaseRespository<InspectionScheme> inspectionSchemeRepository,
            IMapper mapper)
        {
            _incomingInspectionRepository = incomingInspectionRepository;
            _inspectionSchemeRepository = inspectionSchemeRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<IncomingInspectionDto>> Handle(GetIncomingInspectionCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<IncomingInspectionDto>();

            try
            {
                // 关键：关联查询检验方案表（需确保IncomingInspection有导航属性或通过Join关联）
                var query = from inspection in _incomingInspectionRepository.GetAll()
                            join scheme in _inspectionSchemeRepository.GetAll() // 注入检验方案仓储
                              on inspection.InspectionSchemeId equals scheme.Id
                            where inspection.Isdel == false // 过滤未删除的数据
                            select new { inspection, scheme }; // 同时获取来料检验和检验方案数据

                // 应用搜索条件（可根据需要扩展）
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(x =>
                        (x.inspection.InspectionNo != null && x.inspection.InspectionNo.Contains(request.Keyword)) ||
                        (x.scheme.Name != null && x.scheme.Name.Contains(request.Keyword))); // 支持按方案名称搜索
                }

                // 获取总记录数
                result.TotalCount = query.Count();

                // 执行分页查询
                if (result.TotalCount > 0)
                {
                    var pagedData = await query.OrderByDescending(x => x.inspection.CreateTime)
                        .Skip((request.Index - 1) * request.Size)
                        .Take(request.Size)
                        .ToListAsync(cancellationToken); // 异步查询

                    // 映射到DTO（包含检验方案名称）
                    result.PageDatas = pagedData.Select(x => new IncomingInspectionDto
                    {
                        Id = x.inspection.Id,
                        InspectionNo = x.inspection.InspectionNo,
                        InspectionSchemeId = x.inspection.InspectionSchemeId,
                        InspectionSchemeName = x.scheme.Name, // 从关联表获取名称
                        IncomingMaterialsId = x.inspection.IncomingMaterialsId,
                        TotalQuantity = x.inspection.TotalQuantity,
                        Result = x.inspection.Result,
                        State = x.inspection.State,
                        CreateName = x.inspection.CreateName,
                        CreateTime = x.inspection.CreateTime,
                        UpdateName = x.inspection.UpdateName,
                        UpdateTime = x.inspection.UpdateTime,
                        Isdel = x.inspection.Isdel
                    }).ToList();
                }
                else
                {
                    result.PageDatas = new List<IncomingInspectionDto>();
                }

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.PageDatas = new List<IncomingInspectionDto>();
            }

            return result;
        }
    }
}
